<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/28
 * Time: 14:19
 */

namespace app\api\model\VideoUser;


use app\Utils\ImageUtil;
use app\api\model\User\UserModel;
use app\api\model\Index\VideoUser;
use think\Model;
use think\Db;

class VideoUserCommentModel extends Model
{
    /**
     * 数据表名
     * @var string
     */
    protected $name = "video_user_comment";

    public function video()
    {
        return $this->hasOne('app\api\model\Index\VideoUser', 'id', 'video_id');
    }

    /**
     * 分页查询
     * @param $page
     * @param $limit
     * @param $where
     * @return mixed
     * @throws
     */
    public static function getListWhere($page, $limit, $where = [], $field = "*")
    {
        $start = ceil(($page - 1) * $limit);

        $list = self::field($field)->where($where)->limit($start, $limit)->select()->toArray();
        foreach ($list as &$item) {
            $item['userInfo'] = UserModel::getUserWhere([['id', '=', $item['uid']]], 'head_img,nickname');
            $item['userInfo']['head_img'] = ImageUtil::i()->replaceUrl($item['userInfo']['head_img']);
            $item['child'] = VideoUserCommentModel::getChilds($item['id']);
            $item['childnum'] = count($item['child']);

        }
        return $list;

    }

    /**获取所有子集
     * @param $pid
     * @param int $num
     * @param array $arr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getChilds($pid, $num = 0, $arr = [])
    {
        $list = self::where('pid', $pid)->select()->toArray();

        foreach ($list as &$item) {
            $item['userInfo'] = UserModel::getUserWhere([['id', '=', $item['uid']]], 'head_img,nickname');
            $item['userInfo']['head_img'] = ImageUtil::i()->replaceUrl($item['userInfo']['head_img']);

            if ($num > 0) {
                $some = self::where('id', $item['pid'])->value('uid');
                $some = UserModel::getUserWhere([['id', '=', $some]], 'nickname');
                $item['some'] = $some['nickname'];
            } else {
                $item['some'] = null;
            }
            $num++;
            $arr[] = $item;
            $arr = array_merge(self::getChilds($item['id'], $num, $arr));
        }
        return $arr;
    }

    public static function get_top_parentid($id)
    {
        $pid = self::where('id', $id)->value('pid');
        if ($pid == 0) {
            return $id;
        }
        return self::get_top_parentid($pid);
    }

    public static function finds($id)
    {
        $field = 'u.head_img AS user_avatar, u.nickname AS user_nickname, u.id AS user_id, v.id AS video_comment_id, v.content, v.add_time AS time, v.video_id, v.pid AS video_comment_pid, v.num AS num_video_comment_like, v.top AS is_top, v.is_del';
        $result = self::alias('v')
            ->field($field)
            ->join('hd_user u', 'u.id=v.uid', 'LEFT')
            ->where('v.id', $id)
            ->find()
            ->toArray();
        return $result;
    }


    /**无限极排序
     * @param $data
     * @param int $pid
     * @param array $arr
     * @return array
     */
    public static function sort($data, $pid = 0)

    {
        $arr = [];
        foreach ($data as $key => &$value) { //循环操作所有的评论
            if ($value['pid'] == $pid) {   //找出第一个顶级评论
                unset($data[$key]);
                $value['child'] = self::sort($data, $value['id']);
                $arr[] = $value;
            }
        }
        return $arr;
    }


    public static function saves($data)
    {
        //获取视频是否存在
        $row = VideoUser::where('id', '=', $data['video_id'])->count();
        if (!$row) return false;
        $data['add_time'] = date("Y-m-d H:i:s", time());

        $id = self::insertGetId($data);
        if ($id) VideoUser::where('id', '=', $data['video_id'])->inc('nums_discuss')->update();;
        if ($data['pid'] > 0) {
            $pid = self::get_top_parentid($data['pid']);
            self::where('id', '=', $pid)->inc('num')->update();
        }
        return $id;
    }

    public static function dels($where)
    {

        $row = self::where($where)->find();
        if (!$row) return false;

        \think\facade\Db::transaction(function () use ($row, $where) {
            self::where($where)->update(['is_del' => 1, 'top' => 0]);
            \think\facade\Db::name('video_user')->where('id', $row['video_id'])->dec('nums_discuss')->update();
            return true;
        });
        return false;
    }

    /**置顶
     * @param $where
     * @param $top //0：取消 1：置顶
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function top($id, $uid, $top)
    {
        $row = self::where('id', $id)->find();
        if (!$row) return false;
        $where = [
            ['user_id', '=', $uid],
            ['id', '=', $row['video_id']],
        ];
        $video = VideoUser::where($where)->count();
        if (!$video) return false;
        $res = self::where('id', $id)->update(['top' => $top]);
        if ($res) {
            return true;
        }
        return false;
    }

}